package com.itboye.jigongbao.fragments.wagesbillsfragments;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.jigongbao.R;
import com.itboye.jigongbao.activity.HeZhangDetailActivity;
import com.itboye.jigongbao.adpapter.WagesBillsListAdapter;
import com.itboye.jigongbao.app.MyApplication;
import com.itboye.jigongbao.base.BaseFragment;
import com.itboye.jigongbao.bean.JiYiBiBean;
import com.itboye.jigongbao.enums.DetailEnums;
import com.itboye.jigongbao.retrofit.base.ResultEntity;
import com.itboye.jigongbao.retrofit.presenter.UserPrestener;
import com.itboye.jigongbao.utils.Const;
import com.itboye.jigongbao.utils.SPUtils;
import com.itboye.jigongbao.widget.BasePtr;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link WagesBillsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link WagesBillsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WagesBillsFragment extends BaseFragment implements Observer {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    TextView text_test;
    ListView lv_wagesbills;
    private OnFragmentInteractionListener mListener;
    private UserPrestener userPrestener;
    private List<JiYiBiBean.JiYiBiEntity> ar;

    private EditText ed_search;
    private String value;
    private int pageIndex = 1;
    private WagesBillsListAdapter adapter;

    public WagesBillsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WagesBillsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WagesBillsFragment newInstance(String param1, String param2) {
        WagesBillsFragment fragment = new WagesBillsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

//        list_jigongqingdan!!.setOnScrollListener(object : AbsListView.OnScrollListener {
//            override fun onScroll(p0: AbsListView?, p1: Int, p2: Int, p3: Int) {
//                if (p1 == 0) {
//                    var firstVisibleItemView = list_jigongqingdan!!.getChildAt(0)
//                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
//                        Log.d("ListView", "##### 滚动到顶部 #####")
//                        isAtTop = true
//                        isAtBottom = false
//                    }
//                } else if ((p1 + p2) == p3) {
//                    var lastVisibleItemView = list_jigongqingdan!!.getChildAt(list_jigongqingdan!!.getChildCount() - 1);
//                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == list_jigongqingdan!!.getHeight()) {
//                        Log.d("ListView", "##### 滚动到底部 ######")
//                        isAtBottom = true
//                        isAtTop = false
//                    }
//                }
//            }
//
//            override fun onScrollStateChanged(p0: AbsListView?, p1: Int) {
//            }
//
//        })
    }

    public void query(String searchValue) {
//        String today = timeFormat("yyyyMM", System.currentTimeMillis());
        String today = null;
        String role = SPUtils.getSp(Const.Companion.getROLE()).toString();
        if (mParam1.equals("1")) {
            //按项目
            if (role.equals(Const.Companion.getWORKER())) {
                userPrestener.By_JgbRecord_queryWorker(null, searchValue, MyApplication.Companion.getInstance().getLoginInfo().getMobile(), today, 1, 10, getActivity());
            } else {
                userPrestener.By_JgbRecord_queryOverseer(null, searchValue, MyApplication.Companion.getInstance().getLoginInfo().getMobile(), today, 1, 10, getActivity());
            }
        } else {
            //按工头
            if (role.equals(Const.Companion.getWORKER())) {
                userPrestener.By_JgbRecord_queryWorker(searchValue, null, MyApplication.Companion.getInstance().getLoginInfo().getMobile(), today, 1, 10, getActivity());
            } else {
                userPrestener.By_JgbRecord_queryOverseer(searchValue, null, MyApplication.Companion.getInstance().getLoginInfo().getMobile(), today, 1, 10, getActivity());
            }
        }
    }


    // TODO: Rename method, update argument and hook method into UI event

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_wages_bills;
    }

    String role = "";
    PtrFrameLayout ptr_wages_list_framelayout;

    boolean isAtTop = true;
    boolean isAtBottom = false;

    @Override
    protected void initData() {
        role = SPUtils.getSp(Const.Companion.getROLE()).toString();
        BasePtr.setPagedPtrStyle(ptr_wages_list_framelayout);
        initAdapter();
        initListHeader();
        lv_wagesbills.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), HeZhangDetailActivity.class);
                intent.putExtra("title", "明细");
                intent.putExtra("model", (Serializable) ar.get(i));
                if (ar.get(i).getItem_type_key().equals("00S002003")) {
                    intent.putExtra("type", (role.equals(Const.Companion.getFORCEMAN())) ?
                            DetailEnums.YIJIBI_FOREMAN_DIANGONG :
                            DetailEnums.YIJIBI_WORKER_DIANGONG
                    );
                }
                if (ar.get(i).getItem_type_key().equals("00S002002")) {
                    intent.putExtra("type", role.equals(Const.Companion.getFORCEMAN()) ?
                            DetailEnums.YIJIBI_FOREMAN_BAOGONG :
                            DetailEnums.YIJIBI_WORKER_BAOGONG
                    );
                }
                if (ar.get(i).getItem_type_key().equals("00S002004")) {
                    intent.putExtra("type", role.equals(Const.Companion.getFORCEMAN()) ?
                            DetailEnums.YIJIBI_FOREMAN_JIEZHI :
                            DetailEnums.YIJIBI_WORKER_JIEZHI
                    );
                }
                if (ar.get(i).getItem_type_key().equals("00S002005")) {
                    intent.putExtra("type", role.equals(Const.Companion.getFORCEMAN()) ?
                            DetailEnums.YIJIBI_FOREMAN_JIESUAN :
                            DetailEnums.YIJIBI_WORKER_JIESUAN
                    );
                }
                startActivity(intent);

            }
        });
        ptr_wages_list_framelayout.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                pageIndex = 1;
                query(value);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageIndex++;
                query(value);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return isAtTop;
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return isAtBottom;
            }
        });
        userPrestener = new UserPrestener(this);
        query(null);
        ed_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().equals("")) {
                    value = null;
                    query(value);
                }
            }
        });

        ed_search.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = ed_search.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > ed_search.getWidth()
                        - ed_search.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    value = ed_search.getText().toString();
                    query(value);
                }
                return false;
            }
        });
        lv_wagesbills.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0) {
                    View firstVisibleItemView = lv_wagesbills.getChildAt(0);
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        isAtTop = true;
                        isAtBottom = false;
                        Log.d("ListView", "##### 滚动到顶部 #####");
                    }else{
                        isAtTop = false;
                    }
                } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = lv_wagesbills.getChildAt(lv_wagesbills.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == lv_wagesbills.getHeight()) {
                        Log.d("ListView", "##### 滚动到底部 ######");
                        isAtTop = false;
                        isAtBottom = true;
                    }else{
                        isAtBottom = false;
                    }
                }
//                else{
//                    isAtTop = false;
//                    isAtBottom = true;
//                }
            }
        });
    }

    TextView txt_header_jiyibi_list_name, txt_header_jiyibi_list_shouru, txt_header_jiyibi_list_status, txt_header_three;

    private void initListHeader() {
        txt_header_jiyibi_list_name.setText("工头");
        if (mParam1.equals("0")) {
            txt_header_jiyibi_list_name.setVisibility(View.VISIBLE);
            txt_header_jiyibi_list_shouru.setText("时间");
            txt_header_three.setText("分类");
            txt_header_three.setVisibility(View.VISIBLE);
            txt_header_jiyibi_list_status.setText("工钱");
        }else{
            txt_header_jiyibi_list_name.setVisibility(View.GONE);
            txt_header_jiyibi_list_shouru.setText("项目");
            txt_header_three.setText("时间");
            txt_header_three.setVisibility(View.VISIBLE);
            txt_header_jiyibi_list_status.setText("工钱");
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        }
    }

    @Override
    public void update(Observable observable, Object o) {

        ResultEntity entity = (ResultEntity) o;
        ptr_wages_list_framelayout.refreshComplete();
        if (entity.getCode() != 0) {

        } else {
            JiYiBiBean jiYiBiBean = (JiYiBiBean) entity.getData();
            if (pageIndex == 1) {
                ar.clear();
            }
            ar.addAll(jiYiBiBean.getList());
            initAdapter();
        }
    }

    private void initAdapter() {
        if (ar == null) {
            ar = new ArrayList<>();
            adapter = new WagesBillsListAdapter(getActivity(), ar, R.layout.hezhang_list_item);
            adapter.setType(mParam1);
            lv_wagesbills.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
